<template>
  <div class="page-style">
    <div class="flex" style="gap: 20px">
      <change-avatar-btn
        v-if="user"
        v-model:showChangeAvatarDialog="showChangeAvatarDialog"
        class="text-white"
        :objId="user.objId"
      ></change-avatar-btn>
      <q-card class="main-block-with-cropped" style="width: 100%">
        <q-card-section class="text-h6">
          <div class="text-h6">Изменение данных</div>
          <div class="text-subtitle2">Заполните ваш профиль</div>
        </q-card-section>
        <q-card-section v-if="user" class="q-pa-sm">
          <q-list class="row">
            <q-item class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
              <q-item-section side>
                <q-avatar size="100px">
                  <!--                            <img :src="avataroBildo">-->
                  <q-img
                    :loading="imgLoading"
                    :ratio="1"
                    :src="avataroBildo"
                    basic
                    class="rounded-borders"
                    native-context-menu
                    spinner-color="white"
                    style="width: 160px"
                  >
                    <template v-slot:error>
                      <div
                        class="absolute-full flex flex-center bg-negative"
                      ></div>
                    </template>
                  </q-img>
                </q-avatar>
              </q-item-section>
              <q-item-section>
                <q-btn
                  class=""
                  flat
                  label="Загрузить фото"
                  no-caps
                  rounded
                  style="
                    max-width: 120px;
                    background-color: #0fab9d;
                    color: white;
                  "
                  @click="showChangeAvatarDialog = true"
                ></q-btn>
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  class=""
                  v-model="retnomo"
                  :dark="dark"
                  dense
                  label="Псевдоним"
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="chefaRetposhto"
                  :dark="dark"
                  dense
                  label="Email"
                  readonly
                  type="email"
                >
                  <template v-slot:default>
                    <change-email-btn class="q-px-sm" />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input v-model="unuaNomo" :dark="dark" dense label="Имя" />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="duaNomo"
                  :dark="dark"
                  dense
                  label="Отчество"
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="familinomo"
                  :dark="dark"
                  dense
                  label="Фамилия"
                />
              </q-item-section>
            </q-item>
            <q-item
              class="col-lg-12 col-md-12 col-sm-12 col-xs-12"
              v-if="false"
            >
              <q-item-section>
                <q-input
                  v-model="user_details.address"
                  autogrow
                  :dark="dark"
                  dense
                  label="Адрес"
                  readonly
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12" v-if="false">
              <q-item-section>
                <q-input
                  v-model="user_details.city"
                  color="dlack"
                  :dark="dark"
                  dense
                  label="Город"
                  readonly
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="naskighdato"
                  :dark="dark"
                  dense
                  label="Дата рождения"
                  type="date"
                />
              </q-item-section>
            </q-item>
            <q-item
              class="col-lg-12 col-md-12 col-sm-12 col-xs-12"
              v-if="false"
            >
              <q-item-section>
                <q-input
                  v-model="user_details.about"
                  :dark="dark"
                  dense
                  label="Описание"
                  readonly
                  type="textarea"
                />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            class="text-capitalize text-white cursor-pointer"
            flat
            style="background: #0fab9d; margin-right: 15px; margin-bottom: 15px"
            @click="setUzanto"
            >Сохранить
          </q-btn>
        </q-card-actions>
      </q-card>

      <q-form ref="passwordForm" @submit.prevent="setPassword">
        <q-card class="main-block-with-cropped" style="width: 100%">
          <q-card-section class="text-h6">
            <div class="text-h6">Изменить пароль</div>
          </q-card-section>
          <q-card-section class="row q-pa-sm">
            <q-list class="row">
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Текущий пароль </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="password"
                    :dark="dark"
                    dense
                    label="Текущий пароль"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section>
              </q-item>
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Новый пароль </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="newPassword"
                    :rules="passwordRules"
                    :dark="dark"
                    dense
                    label="Новый пароль"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section>
              </q-item>
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Подтверждение пароля </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="confirmPassword"
                    :rules="confirmRules"
                    :dark="dark"
                    dense
                    label="Подтверждение пароля"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section> </q-item
            ></q-list>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              class="text-white"
              flat
              no-caps
              style="
                background: #0fab9d;
                margin-right: 15px;
                margin-bottom: 15px;
              "
              type="submit"
              >Сохранить пароль
            </q-btn>
          </q-card-actions>
        </q-card>
      </q-form>
    </div>
  </div>
</template>
<script>
import { defineAsyncComponent, defineComponent } from "vue";
import { mapState, mapActions } from "pinia";
import { useRegistradoStore } from "src/stores/registrado";
import { useAuthStore } from "src/stores/auth";
import { useUiStore } from "src/stores/UI";
import { useUserStore } from "src/stores/uzanto";

export default defineComponent({
  name: "UserProfile",

  setup() {
    return {
      getPageStyle(offset, height) {
        return {
          height: `${height - offset - 105}px`,
        };
      },
    };
  },

  components: {
    ChangeEmailBtn: defineAsyncComponent(() =>
      import("components/ChangeEmailDialog")
    ),
    ChangeAvatarBtn: defineAsyncComponent(() =>
      import("components/ChangeAvatarDialog")
    ),
  },
  data() {
    return {
      user_details: {},
      password_dict: {},
      showChangeAvatarDialog: false,

      optionsLandoj: this.infoj?.landoj,
      optionsRegiono: this.infoj?.regiono,
      optionsOrganizo: this.infoj?.organizo,
      unuaNomo: null,
      duaNomo: null,
      familinomo: null,
      retnomo: null,
      sovetoj: null,
      sindikatoj: null,
      sekso: null,
      seksoOptions: ["Мужской", "Женский"],
      naskighdato: null,
      loghregiono: null,
      loghlando: null,
      statuso: null,
      chefaTelefonanumero: null,
      chefaRetposhto: null,
      chefaOrganizo: null,
      chefaLingvo: null,
      avataro: null,
      administritajKomunumoj: null,
      changeAvatar: null,
      errors: {},
      tab: "baza",
      uuid: null,
      tabs: [
        {
          tab: "baza",
          nomo: "Основные",
        },
        {
          tab: "sekura",
          nomo: "Безопасность",
        },
        {
          tab: "sciigo",
          nomo: "Уведомления",
        },
      ],

      password: null,
      newPassword: null,
      confirmPassword: null,
      passwordRules: [
        (v) =>
          this.password ? !!v || "Поле обязательно для заполнения" : true,
        (v) =>
          /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) ||
          'Допустимы только символы латинского алфавита, цифры и символы "_*.,;$!?%#=()"',
        (v) =>
          this.password
            ? (v?.length >= 6 && v?.length <= 32) ||
              "Пароль должен иметь длину от 6 до 32 символов"
            : true,
        (v) =>
          !Object.prototype.hasOwnProperty.call(this.errors, "pasvorto") ||
          this.errors.pasvorto,
      ],
      confirmRules: [
        (v) =>
          this.password ? !!v || "Поле обязательно для заполнения" : true,
        (v) =>
          /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) ||
          'Допустимы только символы латинского алфавита, цифры и символы "_*.,;$!?%#=()"',
        (v) => this.newPassword === v || "Пароли не совпадают",
      ],
    };
  },

  watch: {
    user: function () {
      this.fillUzanto();
    },
    regionoKodo: function (cur) {
      this.fetchInfojRegiono({
        lando_Kodo: cur.value || "RU",
      });
    },
  },
  computed: {
    ...mapState(useRegistradoStore, {
      infoj: "getInfoj",
    }),
    ...mapState(useAuthStore, {
      user: "user",
    }),
    ...mapState(useUiStore, {
      dark: "dark",
      imgLoading: "getImageLoadingMode",
    }),
        ...mapState(useAuthStore, ["isLoggedIn"]),


    retlisto: {
      get: function () {
        if (!this.user?.agordoj) return null;
        const curJSON = JSON.parse(this.user.agordoj);
        return Object.prototype.hasOwnProperty.call(curJSON, "abono_shlosilo");
      },
      set: function (val) {
        this.changeUzanto({ poshtoSciigoj: val }).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      },
    },

    seksoLazyFix: function () {
      if (this.sekso === "Мужской") return "vira";
      if (this.sekso === "Женский") return "virina";
      return null;
    },
    regionoKodo: function () {
      if (typeof this.loghlando !== "object") {
        const cur = this.infoj.landoj.filter((v) => {
          return v.label === this.loghlando;
        });
        return cur;
      }
      return this.loghlando;
    },
    selectWidth: function () {
      return this.$refs.selectOrganizo[0].clientWidth;
    },
    avataroBildo: function () {
      return this.avataro.bildoE?.url || this.avataro.bildoF?.url;
    },
  },
  methods: {
    ...mapActions(useRegistradoStore, [
      "fetchInfoj",
      "fetchOrganizo",
      "fetchInfojRegiono",
    ]),
    ...mapActions(useAuthStore, ["addUniversoUzanto"]),
    ...mapActions(useUserStore, ["changeUzanto", "changePassword"]),

    filterLandoj(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsLandoj = this.infoj.landoj.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    filterRegiono(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsRegiono = this.infoj.regiono.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    filterOrganizo(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsOrganizo = this.infoj.organizo.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },

    setUzanto() {
      const retnomo =
        this.retnomo === (this.user.universoUzanto?.retnomo ?? null)
          ? null
          : this.retnomo;
      const params = {
        unuaNomo:
          this.unuaNomo === this.user.unuaNomo?.enhavo ? null : this.unuaNomo,
        duaNomo:
          this.duaNomo === this.user.duaNomo?.enhavo ? null : this.duaNomo,
        familinomo:
          this.familinomo === this.user.familinomo?.enhavo
            ? null
            : this.familinomo,
        sekso:
          this.seksoLazyFix === this.user?.sekso ? null : this.seksoLazyFix,
        naskighdato:
          this.naskighdato === this.user.naskighdato
            ? null
            : this.naskighdato.replace(/\//g, "."),
        chefaOrganizo:
          this.chefaOrganizo.label === this.user.chefaOrganizo?.nomo?.enhavo
            ? null
            : this.chefaOrganizo.value,
        lando:
          this.loghlando?.label === this.user.loghlando?.nomo?.enhavo
            ? null
            : this.loghlando?.value,
        lingvo:
          this.chefaLingvo.label === this.user.chefaLingvo?.nomo
            ? null
            : this.chefaLingvo.value,
        regiono:
          this.loghregiono === this.user.loghregiono?.nomo?.enhavo
            ? null
            : this.loghregiono.value,
        statuso:
          this.statuso === this.user.statuso?.enhavo ? null : this.statuso,
      };
      //тут сокращаю запрос, чтоб были только содержательные параметры (не null или undefined)
      const reducedParams = Object.fromEntries(
        Object.entries(params).filter(
          ([key, value]) => value !== null && value !== undefined
        )
      );
      if (Object.keys(reducedParams).length) {
        this.changeUzanto(reducedParams).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      }
      const vars = { retnomo };
      if (this.uuid) {
        vars.uuid = this.uuid;
      }

      if (retnomo) {
        this.addUniversoUzanto(vars).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      }
    },

    mapErrorObject(errors) {
      const out = {};
      for (const item of errors) {
        out[item.field] = item.message;
      }
      return out;
    },
    onReset() {
      this.fillUzanto();
    },
    fillUzanto() {
      if (this.user) {
        this.unuaNomo = this.user.unuaNomo.enhavo;
        this.duaNomo = this.user.duaNomo.enhavo;
        this.familinomo = this.user.familinomo.enhavo;
        this.retnomo = this.user?.universoUzanto?.retnomo ?? null;
        this.sovetoj = [
          ...new Set(
            this.user.sovetoj.edges.map((cur) => cur.node.nomo.enhavo)
          ),
        ].join(", ");
        this.sindikatoj = [
          ...new Set(
            this.user.sindikatoj.edges.map((cur) => cur.node.nomo.enhavo)
          ),
        ].join(", ");
        this.sekso =
          this.user.sekso === "vira"
            ? "Мужской"
            : this.user.sekso === "virina"
            ? "Женский"
            : "";
        this.naskighdato = this.user.naskighdato;
        this.loghregiono = this.user.loghregiono?.nomo?.enhavo;
        this.loghlando = this.user.loghlando?.nomo?.enhavo;
        this.statuso = this.user.statuso?.enhavo;
        this.chefaTelefonanumero = this.user.chefaTelefonanumero ?? "";
        this.chefaRetposhto = this.user.chefaRetposhto;
        this.chefaOrganizo = this.user.chefaOrganizo?.nomo?.enhavo ?? "";
        this.chefaLingvo = this.user.chefaLingvo?.nomo ?? "";
        this.avataro = this.user.avataro ?? "";
        this.uuid = this.user?.universoUzanto?.uuid ?? null;
        this.administritajKomunumoj = [
          ...new Set(
            this.user.administritajKomunumoj.edges.map(
              (cur) => cur.node.nomo.enhavo
            )
          ),
        ].join(", ");
      }
    },

    setPassword() {
      if (this.newPassword !== this.confirmPassword) {
        this.$q.notify({
          type: "negative",
          message: "Новый пароль не совпадает с подтверждением",
        });
        return;
      }
      const params = {
        uzantoId: this.user.objId,
        pasvorto: this.password,
        novaPasvorto: this.newPassword,
      };
      this.changePassword(params)
        .then((resp) => {
          if (resp?.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.errors = { message: resp?.message };
            this.$refs.passwordForm.validate();
            this.errors = {};
            this.$q.notify({
              type: "negative",
              message: resp?.message,
            });
          }
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.onResetPassword();
        });
    },

    onResetPassword() {
      this.password = this.newPassword = this.confirmPassword = null;
    },
  },
  created() {
    if (process.env.CLIENT) this.fetchInfoj;
    if (process.env.CLIENT) this.fetchOrganizo;

    this.fillUzanto();
  },
});
</script>
